﻿using Abp.UI;

namespace Mt.Site.Core.WorkFlows.Design.DiyForm
{
    internal class ContentDataChecher
    {
        public string Check(ContentDataSecuritySetting setting, string val,string fieldName,FieldType fieldType)
        {
            if(setting == null)
            {
                return val;
            }

            if(fieldType == FieldType.Number || fieldType == FieldType.DateTime)
            {
                decimal ob = 0;
                decimal.TryParse(val, out ob);
                if (setting.Required)
                {
                    if (ob == 0)
                    {
                        throw new UserFriendlyException($"{fieldName}是必填项！");
                    }
                }

                if (setting.MinValue != null)
                {
                    if (ob < (decimal)setting.MinValue.Value)
                    {
                        throw new UserFriendlyException($"{fieldName}不能小于{setting.MinValue.Value}！");
                    }
                }

                if (setting.MaxValue != null)
                {
                    if (ob > (decimal)setting.MaxValue.Value)
                    {
                        throw new UserFriendlyException($"{fieldName}不能大于{setting.MaxValue.Value}！");
                    }
                }

                if (setting.DigitsCountAfterPoint != null)
                {
                    ob = decimal.Round(ob, setting.DigitsCountAfterPoint.Value);
                }

                return ob.ToString();
            }
            else
            {
                if (setting.Required)
                {
                    if (string.IsNullOrEmpty(val))
                    {
                        throw new UserFriendlyException($"{fieldName}是必填项！");
                    }
                }
                if (fieldType == FieldType.Enum && !setting.MultiSeleted)
                {
                    if(val!= null && val.IndexOf(",") >= 0)
                    {
                        throw new UserFriendlyException($"{fieldName}不是多选项！");
                    }
                }
                return val;
            }
        }
    }
}
